package com.demo.ribbon.controller;

import com.demo.common.entity.User;
import com.demo.common.util.R;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@AllArgsConstructor
@RequestMapping("/ribbon")
@Slf4j
public class RibbonController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/test")
    public R testRibbon() {
        String url = "http://user-service/user/getserver";
        return new R<>(this.restTemplate.getForObject(url, User.class));
    }

    @GetMapping("/getClient")
    public R getClient() {
        ServiceInstance instances = loadBalancerClient.choose("user-service");
        String serviceId = instances.getServiceId();
        String host = instances.getHost();
        int port = instances.getPort();
        log.info("负载均衡:" + serviceId + ":" + host + ":" + port);
        return new R<>();
    }
}
